package com.luffyzhao.demo.scheduled;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.luffyzhao.demo.properties.ApplicationProperties;
import com.luffyzhao.demo.utils.FileUtil;
import com.surftools.BeanstalkClient.Client;
import com.surftools.BeanstalkClient.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Component
public class JobConsumer implements Runnable {
    private ApplicationProperties properties;
    @Autowired
    private Client client;

    public JobConsumer(ApplicationProperties properties) {
        super();
        this.properties = properties;
    }

    private void println() {
        for (String s :
                client.listTubesWatched()) {
            logger.info("listTubesWatched:" + s);
        }
        for (String s :
                client.listTubes()) {
            logger.info("listTubes:" + s);
        }

        logger.info("listTubeUsed:" + client.listTubeUsed());
    }

    public void work() {

        try {
            logger.info("开始拉报文");
//            println();
            Job job = null;

            client.watch(properties.getConsumerTube());
            client.ignore("default");
            while ((job = client.reserve(20)) != null) {
                try {
                    // 执行延时的业务逻辑
                    String biz = new String(job.getData());

                    JSONObject obj = JSON.parseObject(biz);

                    FileUtil.writeToTargetDir(
                            obj.getString("message"),
                            obj.getString("name"),
                            this.properties.getSendDir()
                    );


                    logger.info(this.properties.getSendDir() + obj.get("name") + "\n" + obj.getString("message"));

                    // 消费此Job
                    client.delete(job.getJobId());
                } catch (JSONException e) {
                    logger.error("报文件不是正确的 josn 格式：" + e.getMessage());
                } catch (IOException e) {
                    logger.error("报文件保存失败：" + e.getMessage());
                }
            }

            logger.info("结束拉报文");
        } catch (Exception e) {
            logger.error("拉取报文失败：" + e.getMessage());
        }
    }

    public void run() {
        while (true) {
            try {
                this.work();
            } catch (Throwable e) {

            }
        }

    }

    @PostConstruct
    public void init() {
        //启动线程实例
        new Thread(this).start();
    }


    private static Logger logger;

    static {
        JobConsumer.logger = LoggerFactory.getLogger((Class) JobConsumer.class);
    }

}
